/**
 * 
 * 这层时专门处理数据的
 * 
*/
const { exec } = require('../db/mysql'); // 封装的mysql

const getList = (author, keyword) => {
    // 先返回假数据（格式是正确的）
    let sql = `select * from blogs where 1=1 `;
    if (author) {
        sql += `and author='${author}' `
    }
    if (keyword) {
        sql += `and title like '%${keyword}%' `
    }
    sql += `order by createtime desc;`

    // 返回一个promise
    return exec(sql);
}

const getDetail = (id) => {
    // 先返回假数据（格式是正确的）
    let sql = `select * from blogs where id='${id}'`;
    return exec(sql);
}

// 新增博客 blogData = {} 没有值默认为空对象
const newBlog = (blogData = {}) => {
   const title = blogData.title;
   const content = blogData.content;
   const author = blogData.author;
   const createtime = Date.now();

   let sql = `insert into blogs (title, content, author, createtime) values ('${title}', 
             '${content}', '${author}', '${createtime}')`;
   // 返回id          
   return exec(sql).then(insertData => {
       return{
           id: insertData.insertId
       }
   })          
}

// 更新博客
const updateBlog = (id, blogData = {}) => {
    // id 要更新博客的ID
    // blogData 是一个博客对象，包含title content
    let sql = `update blogs set title = '${blogData.title}', 
              content = '${blogData.content}' where id = '${id}'`
    return exec(sql).then(updateData => {
        if (updateData.affectedRows > 0) {
            return true
        }
        return false;
    })
    ;          
}

// 删除博客
const delBlog = (id, author) => {
    // id 要删除博客的ID
    let sql = `delete from blogs where id = '${id}' and author = '${author}'`
    return exec(sql).then(delData => {
      if (delData.affectedRows > 0) {
            return true
        }
        return false;
    })
    ;
}

module.exports = {
    getList,
    getDetail,
    newBlog,
    updateBlog,
    delBlog
}
